package com.example.springboot.project3.service;

import com.example.springboot.project3.dao.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class GetDataService {
    /**
     * 每天凌晨1点执行计划任务，更新data成员变量
     * data成员变量储存着全球新冠病毒统计数据
     *
     */
    @Scheduled(cron = "0 0 1 * * *")   //声明这是一个计划任务。
    public List<RegionStats> getData() throws IOException {
        //用于存放读取出来的数据
        List<RegionStats> data = new ArrayList<>();
        String uriTemplate = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(uriTemplate))
                .headers(httpHeaders -> httpHeaders.add("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"))
                .build();
        ResponseEntity<Resource> response = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = response.getBody();


        //通过Resource对象的getInputStream方法获取csv文件的输入流
        InputStream inputStream = body.getInputStream();

        InputStreamReader reader = new InputStreamReader(inputStream);

        //以下为CSV官网教程的例子改写
        Reader in = new BufferedReader(reader);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        for (CSVRecord record : records) {
//            String lastName = record.get("Last Name");
//            String firstName = record.get("First Name");
            RegionStats stats = new RegionStats();
            stats.setState(record.get("Province/State"));
            stats.setCountry(record.get("Country/Region"));
            stats.setLatestTotalCases(Integer.parseInt((record.get(record.size()-1))));
            stats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
            data.add(stats);
        }
        return data;
    }

}
